03. Creational Patterns
Creational Patterns
A creational design pattern is any design pattern that concerns how objects in your program are created. These patterns can help you manage the creation of objects as your code becomes increasingly complex.
Singleton Pattern
ND079 JPND C2 L03 A03 Creational Patterns
When Are Singletons Useful?
You may want to use a singleton if:
- A class that has only one instance, but no clear owner.
- You want that instance to be available everywhere in your code.
- The instance is initialized only when it's first used (also known as lazy initialization).
Singleton Example
ND079 JPND C2 L03 A04 Demo Singleton
Demo Code
import java.util.Objects;
public final class Database {
private static Database database;
private Database() {}
public static Database getInstance() {
if (database == null) {
database = new Database();
database.connect("/usr/local/data/users.db");
}
return database;
}
// Connects to the remote database.
private void connect(String url) {
Objects.requireNonNull(url);
}
public static void main(String[] args) {
Database a = Database.getInstance();
Database b = Database.getInstance();
System.out.println(a == b);
}
}
By the way, you probably noticed that this Database
class doesn't actually connect to a remote database. The purpose of the code is to demonstrate the singleton design pattern as simply as possible.
SOLUTION:
- A singleton is one instance that is used throughout entire system.
- A singleton is only initialized once.
- Enumeration values (Java `enum` types) are always singletons.